/**
 * 类名：CoursewareAction
 * 创建日期： 2014-11-7 下午2:34:26
 * 
 */
package com.erms.action;

import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import com.erms.bean.Courseware;
import com.erms.bean.FileInfo;
import com.erms.bean.Message;
import com.erms.bean.StudentTeach;
import com.erms.bean.Teach;
import com.erms.bean.User;
import com.erms.dao.CoursewareDAO;
import com.erms.dao.StudentTeachDAO;
import com.erms.dao.TeachDAO;
import com.erms.dao.UserDAO;
import com.erms.domain.CoursewareService;
import com.erms.util.StringUtil;
import com.erms.util.TimeUtil;

/**
 * @author hmb
 *         备注：
 * 
 */
public class CoursewareAction extends BaseAction {

	private static final long	serialVersionUID	= -2445997848379663878L;

	private File				upload;
	private String				uploadContentType;
	private String				uploadFileName;

	private String				teachJson;
	private String				coursewareJson;

	// 表单提交的数据
	private String				description;
	private String				newFileName;
	private String				teachID;

	// dao
	@Resource
	private CoursewareService	coursewareService;
	@Resource
	private CoursewareDAO		coursewareDAO;
	@Resource
	private StudentTeachDAO		studentTeachDAO;
	@Resource
	private UserDAO				userDAO;
	@Resource
	private TeachDAO			teachDAO;

	// 作为json返回结果
	private String				jsonResult			= "";
	
	private String order = "timeInc";
	private Integer pageCount = 1;
	private Integer pageNum = 1;

	public Integer getPageCount() {
		return pageCount;
	}

	public void setPageCount(Integer pageCount) {
		this.pageCount = pageCount;
	}

	public Integer getPageNum() {
		return pageNum;
	}

	public void setPageNum(Integer pageNum) {
		this.pageNum = pageNum;
	}

	public String getCoursewareJson() {

		return coursewareJson;
	}

	public void setCoursewareJson(String coursewareJson) {

		this.coursewareJson = coursewareJson;
	}

	public String getTeachJson() {

		return teachJson;
	}

	public void setTeachJson(String teachJson) {

		this.teachJson = teachJson;
	}

	public String getJsonResult() {

		return jsonResult;
	}

	public void setJsonResult(String jsonResult) {

		this.jsonResult = jsonResult;
	}

	public String getNewFileName() {

		return newFileName;
	}

	public void setNewFileName(String newFileName) {

		this.newFileName = newFileName;
	}

	public String getTeachID() {

		return teachID;
	}

	public void setTeachID(String teachID) {

		this.teachID = teachID;
	}

	public File getUpload() {

		return upload;
	}

	public void setUpload(File upload) {

		this.upload = upload;
	}

	public String getUploadContentType() {

		return uploadContentType;
	}

	public void setUploadContentType(String uploadContentType) {

		this.uploadContentType = uploadContentType;
	}

	public String getUploadFileName() {

		return uploadFileName;
	}

	public void setUploadFileName(String uploadFileName) {

		this.uploadFileName = uploadFileName;
	}

	public String getDescription() {

		return description;
	}

	public void setDescription(String description) {

		this.description = description;
	}

	// 文件上传action
	public String upload() {

		logger.debug("文件描述：" + description);
		logger.debug("文件类型：" + uploadContentType);
		logger.debug("文件名：" + uploadFileName);

		JSONObject result = new JSONObject();
		int timestamp = TimeUtil.getTimeStamp();
		result.put("timestamp", timestamp);

		String userID = (String) getSession().getAttribute(KEY_USERNAME);
		if (StringUtil.isNull(userID)) { return LOGIN; }

		if (coursewareService.save(userID, teachID, upload, uploadFileName,
				uploadContentType, newFileName, description)) {

			FileInfo fileInfo = coursewareService.getFileInfo();
			Courseware courseware = coursewareDAO.findById(coursewareService.getCourseware().getId());
			// 用于反馈本次课件信息
			Map<String, Object> map = getCoursewareMap(courseware.getId(),
					courseware.getTeach().getCourse().getName(), fileInfo);

			result.put("error", 0);
			result.put("courseware", JSONObject.fromObject(map).toString());
		} else {
			result.put("error", 1);
			result.put("msg", "文件保存失败");
		}

		jsonResult = result.toString();
		return JSON;
	}

	/**
	 * @see com.erms.action.BaseAction#execute()
	 * @return
	 * @throws Exception
	 */
	@SuppressWarnings("unchecked")
	@Override
	public String execute() throws Exception {

		// TODO 自动生成的方法存根
		String userID = (String) getSession().getAttribute(KEY_USERNAME);
		String userType = (String) getSession().getAttribute(KEY_TYPE);
		if (StringUtil.isNull(userID)) { return LOGIN; }
		int n = 0;
		List<StudentTeach> studentTeachs = new ArrayList<>();
		List<Teach> teachs = new ArrayList<>();
		if(STUDENT.equals(userType)) {
			studentTeachs = studentTeachDAO.findByProperty(
				"id.user.id", userID);
			n = studentTeachs.size();
		} else {
			teachs = teachDAO.findByTeacherId(userID);
			n = teachs.size();
		}

		List<Courseware> coursewareList = new ArrayList<>();
		List<Map<String, String>> teachList = new ArrayList<>();
		for (int i = 0; i < n; i++) {
			Teach teach;
			if(STUDENT.equals(userType)) {
				teach = studentTeachs.get(i).getId().getTeach();
			} else {
				teach = teachs.get(i);
			}
			Map<String, String> map = new HashMap<String, String>();
			String courseName = teach.getCourse().getName();
			map.put("id", teach.getId());
			map.put("name", courseName);
			List<Courseware> tempCoursewares = coursewareDAO.findByProperty(
					"teach.id", teach.getId());
			coursewareList.addAll(tempCoursewares);
			teachList.add(map);
		}
		teachJson = JSONArray.fromObject(teachList).toString();
		
		if ("timeInc".equals(order)) {
			Collections.sort(coursewareList, new Comparator<Courseware>() {
				@Override
				public int compare(Courseware o1, Courseware o2) {
					// TODO Auto-generated method stub
					return o1.getFileInfo().getTimestamp().compareTo(o2.getFileInfo().getTimestamp());
				}
			});
		} else if ("timeDec".equals(order)) {
			Collections.sort(coursewareList, new Comparator<Courseware>() {
				@Override
				public int compare(Courseware o1, Courseware o2) {
					// TODO Auto-generated method stub
					return o2.getFileInfo().getTimestamp().compareTo(o1.getFileInfo().getTimestamp());
				}
			});
		} else if ("teachInc".equals(order)) {
			Collections.sort(coursewareList, new Comparator<Courseware>() {
				@Override
				public int compare(Courseware o1, Courseware o2) {
					// TODO Auto-generated method stub
					return o1.getTeach().getId()
							.compareTo(o2.getTeach().getId());
				}
			});
		} else if ("teachDec".equals(order)) {
			Collections.sort(coursewareList, new Comparator<Courseware>() {
				@Override
				public int compare(Courseware o1, Courseware o2) {
					// TODO Auto-generated method stub
					return o2.getTeach().getId()
							.compareTo(o1.getTeach().getId());
				}
			});
		}
		int len = coursewareList.size();
		List<Courseware> tempList = new ArrayList<>();
		pageCount = (len % 5 == 0) ? (len / 5) : (len / 5 + 1);
		if (pageCount == 0)
			pageCount = 1;
		if (pageNum >= 1 && pageNum <= pageCount) {
			tempList.addAll(coursewareList.subList((pageNum - 1) * 5,
					(pageNum * 5 <= len) ? (pageNum * 5) : len));
		}
		List<Map<String, Object>> listToJsonList = new ArrayList<>();
		for (Courseware courseware : tempList) {
			FileInfo fileInfo = courseware.getFileInfo();
			listToJsonList.add(getCoursewareMap(
					courseware.getId(), courseware.getTeach().getCourse().getName(), fileInfo));
		}
		coursewareJson = JSONArray.fromObject(listToJsonList).toString();
		return super.execute();
	}

	private Map<String, Object> getCoursewareMap(Integer courseID,
			String courseName, FileInfo fileInfo) {
		String userID = fileInfo.getUser().getId();
		User tempUser = userDAO.findById(userID);
		
		Map<String, Object> map = new HashMap<>();
		map.put("coursewareID", courseID);
		map.put("id", fileInfo.getId());
		map.put("course", courseName);
		String fullName = fileInfo.getName();
		int a = fullName.lastIndexOf("_");
		int b = fullName.lastIndexOf(".");
		if (a != -1 && b != -1) {
			map.put("name", fullName.substring(0, a) + fullName.substring(b));
		} else {
			map.put("name", fullName);
		}
		map.put("user", tempUser.getName() == null
				? tempUser.getId()
				: tempUser.getName());
		map.put("userid", userID);
		map.put("type", fileInfo.getType());
		map.put("size", String.valueOf(fileInfo.getSize() / 1000l) + "kb");
		map.put("time", TimeUtil.format(fileInfo.getTimestamp()));
		map.put("description", fileInfo.getDescription());
		map.put("downNum",
				fileInfo.getDownloadNum() == null ? 0 : fileInfo
						.getDownloadNum());
		map.put("commentNum",
				fileInfo.getCommentNum() == null ? 0 : fileInfo.getCommentNum());
		map.put("readNum", fileInfo.getReadNum() == null ? 0 : fileInfo
				.getReadNum().toString());

		return map;
	}

	public String getOrder() {
		return order;
	}

	public void setOrder(String order) {
		this.order = order;
	}
}
